import mockjs from 'mockjs'
import { defineMock } from 'umi'

// 存储已登录用户的 token
const loggedInTokens = new Set()

function parseAuthToken(authHeader: string) {
  if (!authHeader) {
    return null
  }
  const parts = authHeader.split(' ')
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    return null
  }
  return parts[1]
}

export default defineMock({
  // 获取用户信息
  'GET /api/user/current': (req, res) => {
    // 从请求头中获取 Authorization
    const authHeader = req.headers.authorization
    const token = parseAuthToken(authHeader ? authHeader : '')

    // 检查是否存在 token 且有效
    if (!token || !loggedInTokens.has(token)) {
      res.status(401).json({
        code: 401,
        data: null,
        message: '未登录或登录已过期',
      })
      return
    }

    // 返回用户信息
    res.json({
      code: 200,
      data: {
        id: 1,
        username: 'admin',
        nickname: '管理员',
        avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
        email: 'admin@example.com',
        phone: '13800138000',
        roles: ['admin'],
        permissions: ['*:*:*'],
        loginTime: '2025-10-24T09:00:00Z',
      },
      message: '操作成功',
    })
  },

  // 用户登录
  'POST /api/user/login': (req, res) => {
    const { username, password } = req.body

    // 模拟登录验证逻辑
    if (username === 'admin' && password === 'admin123') {
      const token = mockjs.mock('@guid')
      // 将 token 添加到已登录集合中
      loggedInTokens.add(token)

      res.json({
        code: 200,
        data: {
          token: token,
          expireTime: '2025-10-25T09:00:00Z',
        },
        message: '登录成功',
      })
    } else {
      res.status(401).json({
        code: 401,
        data: null,
        message: '用户名或密码错误',
      })
    }
  },

  // 用户登出
  'GET /api/user/logout': (req, res) => {
    // 从请求头中获取 Authorization
    const authHeader = req.headers.authorization

    // 删除 token
    if (authHeader) {
      const token = parseAuthToken(authHeader)
      loggedInTokens.delete(token)
    }

    res.json({
      code: 200,
      data: null,
      message: '退出成功',
    })
  },
})
